#!/usr/bin/env python
# -*- coding: utf-8 -*-

from PyQt6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout, QHBoxLayout, 
                            QPushButton, QFileDialog, QLabel, QGridLayout, 
                            QScrollArea, QSizePolicy, QTabWidget)
from PyQt6.QtCore import Qt, QSize, QRect
from PyQt6.QtGui import QIcon, QPixmap
import os
import zipfile
from PIL import Image
from io import BytesIO

from comic_viewer import ComicViewer
from utils import ComicUtils
from config_manager import ConfigManager

class FlowWidget(QWidget):
    """自适应流式布局控件"""
    
    def __init__(self, parent=None):
        super().__init__(parent)
        self.items = []
        self.spacing = 10
        
    def addWidget(self, widget):
        """添加控件到流式布局"""
        self.items.append(widget)
        widget.setParent(self)
        self.updateLayout()
        
    def clearWidgets(self):
        """清空所有控件"""
        for item in self.items:
            item.deleteLater()
        self.items.clear()
        self.updateLayout()
        
    def updateLayout(self):
        """更新布局"""
        if not self.items:
            self.setMinimumHeight(0)
            return
            
        # 获取可用宽度
        available_width = self.width()
        if available_width <= 0:
            available_width = 800  # 默认宽度
            
        # 计算每行可以放置的控件数量
        item_width = 180 + self.spacing  # 控件宽度 + 间距
        items_per_row = max(1, (available_width + self.spacing) // item_width)
        
        # 计算行数
        total_items = len(self.items)
        rows = (total_items + items_per_row - 1) // items_per_row
        
        # 设置控件位置
        for i, item in enumerate(self.items):
            row = i // items_per_row
            col = i % items_per_row
            
            x = col * item_width
            y = row * (280 + self.spacing)  # 控件高度 + 间距
            
            item.setGeometry(QRect(x, y, 180, 280))
            item.show()
            
        # 设置容器的最小高度
        if rows > 0:
            total_height = rows * (280 + self.spacing) - self.spacing
            self.setMinimumHeight(total_height)
        else:
            self.setMinimumHeight(0)
            
    def resizeEvent(self, event):
        """窗口大小改变时重新布局"""
        super().resizeEvent(event)
        self.updateLayout()

class MainWindow(QMainWindow):
    """漫画阅读器主窗口类"""
    
    def __init__(self):
        super().__init__()
        
        # 设置窗口属性
        self.setWindowTitle("漫画阅读器")
        self.setMinimumSize(800, 600)
        
        # 初始化UI
        self.init_ui()
        
        # 初始化变量
        self.current_dir = ""
        self.comic_files = []
        self.config_manager = ConfigManager()
        self.selected_widget = None  # 当前选中的漫画卡片
        
        # 自动加载上次的目录
        self.auto_load_last_directory()
    
    def create_tabs(self):
        """创建四个标签页"""
        # 创建四个标签页的滚动区域和流式布局
        self.tabs = {}
        tab_names = ["全部", "未看", "已看", "收藏"]
        
        for tab_name in tab_names:
            # 创建标签页
            tab_widget = QWidget()
            
            # 创建布局
            tab_layout = QVBoxLayout(tab_widget)
            
            # 创建滚动区域
            scroll_area = QScrollArea()
            scroll_area.setWidgetResizable(True)
            scroll_area.setHorizontalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
            scroll_area.setVerticalScrollBarPolicy(Qt.ScrollBarPolicy.ScrollBarAsNeeded)
            
            # 创建流式布局容器
            flow_container = FlowWidget()
            flow_container.setMinimumWidth(800)
            
            scroll_area.setWidget(flow_container)
            tab_layout.addWidget(scroll_area)
            
            # 保存引用
            self.tabs[tab_name] = {
                'widget': tab_widget,
                'scroll_area': scroll_area,
                'flow_container': flow_container
            }
            
            # 添加到标签页控件
            self.tab_widget.addTab(tab_widget, tab_name)
        
    def init_ui(self):
        """初始化用户界面"""
        # 创建菜单栏
        self.create_menu_bar()
        
        # 创建中央部件
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        
        # 创建主布局
        main_layout = QVBoxLayout(central_widget)
        
        # 创建标签页控件
        self.tab_widget = QTabWidget()
        main_layout.addWidget(self.tab_widget)
        
        # 创建四个标签页
        self.create_tabs()
        
        # 添加状态栏
        self.statusBar().showMessage("就绪")
    
    def create_menu_bar(self):
        """创建菜单栏"""
        menubar = self.menuBar()
        
        # 创建文件菜单
        file_menu = menubar.addMenu('文件')
        
        # 添加选择漫画目录菜单项
        select_dir_action = file_menu.addAction('选择漫画目录')
        select_dir_action.setShortcut('Ctrl+O')
        select_dir_action.setStatusTip('选择包含漫画ZIP文件的目录')
        select_dir_action.triggered.connect(self.select_directory)
        
        # 添加分隔符
        file_menu.addSeparator()
        
        # 添加刷新菜单项
        refresh_action = file_menu.addAction('刷新')
        refresh_action.setShortcut('F5')
        refresh_action.setStatusTip('重新读取当前漫画目录')
        refresh_action.triggered.connect(self.refresh_comics)
        
        # 添加分隔符
        file_menu.addSeparator()
        
        # 添加退出菜单项
        exit_action = file_menu.addAction('退出')
        exit_action.setShortcut('Ctrl+Q')
        exit_action.setStatusTip('退出程序')
        exit_action.triggered.connect(self.close)
        
    def auto_load_last_directory(self):
        """自动加载上次选择的目录"""
        last_dir = self.config_manager.get_last_directory()
        if last_dir and os.path.exists(last_dir):
            self.current_dir = last_dir
            self.statusBar().showMessage(f"已自动加载目录: {last_dir}")
            self.load_comics(last_dir)
        else:
            self.statusBar().showMessage("请选择漫画目录")
    
    def select_directory(self):
        """选择漫画目录"""
        directory = QFileDialog.getExistingDirectory(self, "选择漫画目录")
        if directory:
            self.current_dir = directory
            # 保存目录到配置文件
            self.config_manager.set_last_directory(directory)
            self.statusBar().showMessage(f"已选择目录: {directory}")
            self.load_comics(directory)
    
    def add_widget_to_adaptive_layout(self, tab_name, widget):
        """将控件添加到自适应布局"""
        if tab_name in self.tabs:
            flow_container = self.tabs[tab_name]['flow_container']
            flow_container.addWidget(widget)
    
    def load_comics(self, directory):
        """加载指定目录下的所有ZIP漫画文件"""
        # 清空之前的漫画列表
        self.comic_files = []
        
        # 重置选中状态
        self.selected_widget = None
        
        # 清空所有标签页的流式布局
        for tab_name, tab_info in self.tabs.items():
            flow_container = tab_info['flow_container']
            flow_container.clearWidgets()
        
        # 检查目录是否存在
        if not os.path.exists(directory):
            ComicUtils.show_error_message(self, "错误", f"目录不存在: {directory}")
            self.statusBar().showMessage(f"错误: 目录不存在: {directory}")
            return
            
        # 检查是否为目录
        if not os.path.isdir(directory):
            ComicUtils.show_error_message(self, "错误", f"不是有效的目录: {directory}")
            self.statusBar().showMessage(f"错误: 不是有效的目录: {directory}")
            return
        
        # 获取目录下所有ZIP文件
        try:
            files = [f for f in os.listdir(directory) if f.lower().endswith('.zip')]
            self.comic_files = files
            
            if not files:
                ComicUtils.show_info_message(self, "提示", "所选目录中未找到ZIP文件")
                self.statusBar().showMessage("未找到ZIP文件")
                return
            
            # 加载并显示漫画封面
            valid_comics = 0
            
            # 为每个标签页初始化计数器
            tab_counters = {tab_name: 0 for tab_name in self.tabs.keys()}
            
            for file_name in files:
                file_path = os.path.join(directory, file_name)
                
                # 检查是否为有效的ZIP文件
                if not ComicUtils.is_valid_zip(file_path):
                    self.statusBar().showMessage(f"跳过无效的ZIP文件: {file_name}")
                    continue
                
                # 获取标记状态
                is_viewed = self.config_manager.is_viewed(file_path)
                is_favorite = self.config_manager.is_favorite(file_path)
                
                # 创建封面控件
                cover_widget = self.create_cover_widget(file_path, file_name)
                valid_comics += 1
                
                # 确定应该显示在哪些标签页
                tabs_to_show = ["全部"]  # 全部标签页总是显示
                
                if is_viewed:
                    tabs_to_show.append("已看")
                if is_favorite:
                    tabs_to_show.append("收藏")
                if not is_viewed and not is_favorite:
                    tabs_to_show.append("未看")
                
                # 在相应的标签页中添加封面控件
                for tab_name in tabs_to_show:
                    if tab_name in self.tabs:
                        # 为每个标签页创建独立的封面控件副本
                        if tab_name == "全部":
                            widget_to_add = cover_widget
                        else:
                            widget_to_add = self.create_cover_widget(file_path, file_name)
                        
                        # 使用自适应布局添加控件
                        self.add_widget_to_adaptive_layout(tab_name, widget_to_add)
                        tab_counters[tab_name] += 1
            
            if valid_comics > 0:
                self.statusBar().showMessage(f"已加载 {valid_comics} 个漫画文件")
            else:
                ComicUtils.show_warning_message(self, "警告", "未找到有效的漫画文件")
                self.statusBar().showMessage("未找到有效的漫画文件")
            
        except PermissionError:
            ComicUtils.show_error_message(self, "错误", f"无权限访问目录: {directory}")
            self.statusBar().showMessage(f"错误: 无权限访问目录: {directory}")
        except Exception as e:
            ComicUtils.show_error_message(self, "错误", f"加载漫画出错: {str(e)}")
            self.statusBar().showMessage(f"加载漫画出错: {str(e)}")
    
    def create_cover_widget(self, file_path, file_name):
        """创建漫画封面控件"""
        # 创建封面容器
        cover_widget = QWidget()
        cover_widget.setFixedSize(180, 280)  # 增加高度以容纳标记按钮
        cover_widget.setStyleSheet("background-color: #2D2D2D; border-radius: 5px; border: 1px solid #3A3A3A;")
        
        # 添加点击事件处理
        cover_widget.mousePressEvent = lambda event: self.select_comic_widget(cover_widget)
        
        # 创建封面布局
        cover_layout = QVBoxLayout(cover_widget)
        cover_layout.setContentsMargins(5, 5, 5, 5)
        
        # 创建封面图片标签
        cover_label = QLabel()
        cover_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        cover_label.setMinimumSize(160, 180)  # 调整高度
        cover_label.setStyleSheet("background-color: #1A1A1A; border-radius: 3px;")
        
        # 使用工具类从ZIP文件中提取封面
        cover_pixmap, image_files_or_error = ComicUtils.extract_cover_image(file_path)
        
        if cover_pixmap:
            # 成功提取到封面
            cover_label.setPixmap(cover_pixmap)
            
            # 存储文件路径和图片列表，用于双击打开
            cover_label.file_path = file_path
            cover_label.image_files = image_files_or_error  # 这里是图片文件列表
            
            # 添加双击事件
            cover_label.mouseDoubleClickEvent = lambda event, path=file_path, images=image_files_or_error: self.open_comic(path, images)
        else:
            # 提取封面失败，显示错误信息
            error_message = image_files_or_error  # 这里是错误信息
            cover_label.setText(error_message)
            
            if "无效的ZIP文件" in error_message:
                self.statusBar().showMessage(f"错误: {file_name} 不是有效的ZIP文件")
            elif "未找到图片文件" in error_message:
                self.statusBar().showMessage(f"警告: {file_name} 中未找到图片文件")
            else:
                self.statusBar().showMessage(f"错误: 加载 {file_name} 时出错: {error_message}")
        
        # 创建标记按钮布局
        mark_layout = QHBoxLayout()
        
        # 创建已看标记按钮
        viewed_btn = QPushButton("已看")
        viewed_btn.setFixedSize(70, 25)
        viewed_btn.setCheckable(True)
        viewed_btn.setChecked(self.config_manager.is_viewed(file_path))
        viewed_btn.clicked.connect(lambda checked, path=file_path: self.toggle_viewed_mark(path, viewed_btn))
        self.update_viewed_button_style(viewed_btn, self.config_manager.is_viewed(file_path))
        
        # 创建收藏标记按钮
        favorite_btn = QPushButton("收藏")
        favorite_btn.setFixedSize(70, 25)
        favorite_btn.setCheckable(True)
        favorite_btn.setChecked(self.config_manager.is_favorite(file_path))
        favorite_btn.clicked.connect(lambda checked, path=file_path: self.toggle_favorite_mark(path, favorite_btn))
        self.update_favorite_button_style(favorite_btn, self.config_manager.is_favorite(file_path))
        
        mark_layout.addWidget(viewed_btn)
        mark_layout.addWidget(favorite_btn)
        
        # 创建标题标签
        title_label = QLabel(file_name)
        title_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        title_label.setWordWrap(True)
        title_label.setStyleSheet("color: white; font-size: 11px;")
        
        # 添加到布局
        cover_layout.addWidget(cover_label)
        cover_layout.addLayout(mark_layout)
        cover_layout.addWidget(title_label)
        
        return cover_widget
    
    def refresh_comics(self):
        """刷新当前漫画目录"""
        if self.current_dir:
            self.statusBar().showMessage("正在刷新漫画目录...")
            self.load_comics(self.current_dir)
        else:
            ComicUtils.show_info_message(self, "提示", "请先选择一个漫画目录")
            self.statusBar().showMessage("请先选择漫画目录")
    
    def toggle_viewed_mark(self, file_path, button):
        """切换已看标记"""
        is_viewed = button.isChecked()
        self.config_manager.set_viewed(file_path, is_viewed)
        self.update_viewed_button_style(button, is_viewed)
        
        status = "已标记为已看" if is_viewed else "已取消已看标记"
        self.statusBar().showMessage(status)
        
        # 刷新标签页显示
        if self.current_dir:
            self.load_comics(self.current_dir)
    
    def toggle_favorite_mark(self, file_path, button):
        """切换收藏标记"""
        is_favorite = button.isChecked()
        self.config_manager.set_favorite(file_path, is_favorite)
        self.update_favorite_button_style(button, is_favorite)
        
        status = "已添加到收藏" if is_favorite else "已从收藏中移除"
        self.statusBar().showMessage(status)
        
        # 刷新标签页显示
        if self.current_dir:
            self.load_comics(self.current_dir)
    
    def update_viewed_button_style(self, button, is_viewed):
        """更新已看按钮样式"""
        if is_viewed:
            button.setStyleSheet("""
                QPushButton {
                    background-color: #4CAF50;
                    color: white;
                    border: none;
                    border-radius: 3px;
                    font-size: 10px;
                    font-weight: bold;
                }
                QPushButton:hover {
                    background-color: #45a049;
                }
            """)
        else:
            button.setStyleSheet("""
                QPushButton {
                    background-color: #555555;
                    color: #CCCCCC;
                    border: 1px solid #777777;
                    border-radius: 3px;
                    font-size: 10px;
                }
                QPushButton:hover {
                    background-color: #666666;
                }
            """)
    
    def update_favorite_button_style(self, button, is_favorite):
        """更新收藏按钮样式"""
        if is_favorite:
            button.setStyleSheet("""
                QPushButton {
                    background-color: #FF9800;
                    color: white;
                    border: none;
                    border-radius: 3px;
                    font-size: 10px;
                    font-weight: bold;
                }
                QPushButton:hover {
                    background-color: #F57C00;
                }
            """)
        else:
            button.setStyleSheet("""
                QPushButton {
                    background-color: #555555;
                    color: #CCCCCC;
                    border: 1px solid #777777;
                    border-radius: 3px;
                    font-size: 10px;
                }
                QPushButton:hover {
                    background-color: #666666;
                }
            """)

    def select_comic_widget(self, widget):
        """选中漫画卡片"""
        # 如果之前有选中的卡片，取消其高亮
        if self.selected_widget and self.selected_widget != widget:
            self.set_widget_highlight(self.selected_widget, False)
        
        # 设置当前卡片为选中状态
        self.selected_widget = widget
        self.set_widget_highlight(widget, True)
    
    def set_widget_highlight(self, widget, highlighted):
        """设置卡片高亮状态"""
        if highlighted:
            # 高亮样式：橙色边框
            widget.setStyleSheet("""
                QWidget {
                    background-color: #2D2D2D; 
                    border-radius: 5px; 
                    border: 1px solid #FF9800;
                }
            """)
        else:
            # 普通样式：灰色边框
            widget.setStyleSheet("""
                QWidget {
                    background-color: #2D2D2D; 
                    border-radius: 5px; 
                    border: 1px solid #3A3A3A;
                }
            """)

    def open_comic(self, file_path, image_files):
        """打开漫画阅读窗口"""
        self.comic_viewer = ComicViewer(file_path, image_files)
        self.comic_viewer.show()